<?php
namespace frontend\models;

use common\models\User;
use common\Yii01;
use yii\base\ErrorException;
use yii\base\Model;
use Yii;
use common\models\Post;
use yii\web\UploadedFile;

/**
 * Post form
 */
class PicForm extends Model
{
    public $title;
    public $cid2;
    public $content;
    public $thumb;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required','message'=>'请输入标题'],
            [['cid2'], 'required','message'=>'请选择分类'],
            [['content'], 'string'],
            [['cid2',], 'integer'],
            [['title'], 'string', 'max' => 255],

            [['thumb'], 'file', 'extensions' => 'jpg, bmp,gif,png', 'mimeTypes' => 'image/jpeg,image/bmp,image/gif, image/png',],
        ];
    }


    public function createPost()
    {
        if ($this->validate()) {
            $user = User::findOne(Yii::$app->user->id);
            //登录用户发帖45秒间隔限制
//            if (time() - $user->last_post < 45) {
//                return false;
//            }
            $user->last_post = time();
            $user->save();
            //保存用的发布的文章
            $post = new Post();
            $post->title = htmlspecialchars($this->title);
            $post->content = htmlspecialchars($this->content); //xss
            $post->cate_id = $this->cid2;
            $post->user_id = Yii::$app->user->id;
            $post->status = 1;
            $post->ip_address = Yii::$app->request->getUserIP();
            $post->signature = $user->signature;
            $post->nickname = $user->nickname;
            $post->img = $user->img;
            $post->create_at = time();
            $post->type =2;
            $thumb = UploadedFile::getInstance($this, 'thumb');
            if ($thumb) {
                $dir = 'uploads/' . date("Ym");
                if (!file_exists($dir)) {
                    mkdir($dir);
                }
                $file_path = $dir . "/" . time() . rand(0, 99) . "." . $thumb->getExtension();
                $thumb->saveAs($file_path);
                $post->thumb = $file_path;
            }

            //如果发布成功  跳转到帖子详情页
            if ($post->save()) {
                return $post;
            }
        }

        return false;
    }
}
